var logger = require('tracer').console();
var dateFormat = require('dateformat');
var express = require('express')
var session = require('express-session')
var app = express()

var db = require('./db')
const PREFIX = '/gpssignin'

// session
app.use(session({ secret: 'gpssign_server', cookie: { maxAge: 24*60*60 }}))

// register
app.post(PREFIX+'/register', function(req, res, next) {
  logger.debug('/register')
  var phone = req.query.phone
  var password = req.query.password
  var name = req.query.name

  if (db.userAlreadyExists(phone)) {
    res.sendStatus(400)
    logger.error('phone[%s] register error', phone)
    return
  }

  db.saveUser({
    phone,
    password,
    name,
  }, function(err) {
    if (err) {
      logger.error('/register saveUser error: ', err)
      res.sendStatus(500)
      return
    }

    res.sendStatus(200)
    logger.debug('phone[%s] register success', phone)
  })
})

// login
app.post(PREFIX+'/login', function(req, res, next) {
  console.log('/login')
  var sess = req.session
  // TODO 验证用户名密码成功后，设置session中uid
  sess.uid = 123456
})

// TODO global gps data
var date = "2017-11-10 20:40"
  , lon = 118.73251738
  , lat = 31.97559901

// update gps
app.post(PREFIX+'/gps', function(req, res, next) {
  console.log('/gps')

  lon = parseFloat(req.query.lon)
  lat = parseFloat(req.query.lat)
  date = dateFormat(new Date(), 'yyyy-mm-dd hh:MM')

  console.log('/gps: date: ' + date + ', lon: ' + lon + ', lat: ' + lat)
})

// query gps
app.get(PREFIX+'/querygps', function(req, res, next) {
  console.log('/querygps: date: ' + date + ', lon: ' + lon + ', lat: ' + lat)
  res.json({date, lon, lat})
})

// static
app.use(express.static('public'))

app.listen(8091)
console.log('Listening on port 8091')
